package com.yl.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yl.mode2.TActOrder2;
import com.yl.model.TActOrder;
import com.yl.model.TActivity;
import com.yl.pay.UnionPay;
import com.yl.pay.WxPay;
import com.yl.result.APIException;
import com.yl.service.TActOrderService;
import com.yl.service.TActivityService;
import com.yl.utils.UnionPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@Api(value = "由来")
@RestController
@RequestMapping("/lyPay")
@Slf4j
public class YlController {
    @Autowired
    UnionPay unionPay;
    @Autowired
    WxPay wxPay;
    @Autowired
    TActOrderService tActOrderService;

    @Autowired
    TActivityService tActivityService;


    @ApiOperation(value = "下单接口")
    /**
     * 下单
     * @param name
     * @param mobile
     * @return
     */
    @GetMapping("/placeOrder")
    public Long placeOrder(@ApiParam(value = "用户名称")String name,@ApiParam(value = "手机号码") String mobile){
//        UserVo userVo=UserVo.getUserVo();
        TActOrder order = tActOrderService.createOrder(name, mobile);
        return order.getOrderId();
    }

    @ApiOperation(value = "下单接口")
    /**
     * 下单
     * @param name
     * @param mobile
     * @return
     */
    @GetMapping("/placeOrderNow")
    public Long placeOrderNow(@ApiParam(value = "用户名称")String name,@ApiParam(value = "手机号码") String mobile,
                              @ApiParam(value = "活动ID") String actId,@ApiParam(value = "数量") String number,
                              @ApiParam(value = "支付类型") String payType,@ApiParam(value = "经度",required=false)String longitude,
                              @ApiParam(value = "纬度",required=false) String latitude,@ApiParam(value = "学校名称",required=false) String school,
                              @ApiParam(value = "年级",required=false) String grade,@ApiParam(value = "班级名称",required=false) String className,
                              @ApiParam(value = "openId",required=false) String openId, @ApiParam(value = "unionId",required=false) String unionId,
                              @ApiParam(value = "所属地区",required=false) String region, @ApiParam(value = "地址",required=false) String address,
                              @ApiParam(value = "邮编",required=false) String postCode,@ApiParam(value = "门票预约时间",required=false) String takeTicketDate,
                              @ApiParam(value = "优惠券使用金额",required=false) String couponAmount){
        log.info("#### openId = " + openId);

        TActOrder2 tActOrder2 = new TActOrder2(name, mobile, actId, number, payType,longitude, latitude, school, grade, className,openId,unionId,region, address, postCode,takeTicketDate,couponAmount);
        TActivity tActivity = tActivityService.findActivityById(actId);
        tActOrder2.setEnterpriseId(tActivity.getActEnterpriseId());
        TActOrder order = tActOrderService.createOrder(tActOrder2);
        return order.getOrderId();
    }


    @ApiOperation(value = "领取优惠券接口")
    /**
     * 领取优惠券接口
     * @return
     */
    @GetMapping("/getCoupon")
    public Long getCoupon(@ApiParam(value = "openId") String openId, @ApiParam(value = "优惠券ID") String couponId){
        log.info("#### openId = " + openId);
        return null;
    }

    @ApiOperation(value = "下单接口")
    /**
     * 下单
     * @param name
     * @param mobile
     * @return
     */
    @PostMapping("/placeOrderByJSON")
    public Long placeOrderByJSON(@ApiParam("订单JSON") @RequestBody TActOrder2 tActOrder2){
//        UserVo userVo=UserVo.getUserVo();
        TActivity tActivity = tActivityService.findActivityById(String.valueOf(tActOrder2.getActId()));
        tActOrder2.setEnterpriseId(tActivity.getActEnterpriseId());

        TActOrder order = tActOrderService.createOrder(tActOrder2);
        return order.getOrderId();
    }


    @ApiOperation("获取订单列表")
    /**
     * 获取订单列表
     * @return
     */
    @GetMapping("/orderList")
    public IPage<TActOrder> orderList(@RequestParam("openId") String openId,@ApiParam("订单类型 0-未支付，1-已支付")String type, @ApiParam("开始页")Integer pageIndex, @ApiParam("每页数量")Integer pageSize){
        //UserVo userVo = UserVo.getUserVo();
        //return tActOrderService.getOrderListByUserAndType(userVo.getUserId(),type,pageIndex,pageSize);
        //log.info("openId =" + openId + "  type=" + type + "  pageIndex = " + pageIndex + "   pageSize = " + pageSize);
        return tActOrderService.getOrderListByOpenId(openId, type, pageIndex, pageSize);
    }

    @ApiOperation(value = "云闪付支付",notes = "1元购支付方法")
    @GetMapping("/unionPay")
    public void unionPay(HttpServletResponse response,@ApiParam("订单id") String orderId){
        try {
            if(orderId == null || orderId.equals("")) {
                log.error("订单编号为空，无法进行支付！");
                throw new APIException("订单编号为空，无法进行支付！");
            }

            String urlPay= tActOrderService.unionPay(orderId);
            log.info(urlPay);
            response.sendRedirect(urlPay);
//            return urlPay;
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new APIException("支付失败！");
    }

    @ApiOperation(value = "微信支付",notes = "1元购支付方法")
    @GetMapping("/wxPay")
    public void wxPay(HttpServletResponse response,@ApiParam("订单id") String orderId,@ApiParam("活动id") String actId){
        try {
            if(orderId == null || orderId.equals("")) {
                log.error("订单编号为空，无法进行支付！");
                throw new APIException("订单编号为空，无法进行支付！");
            }
            if(actId == null || actId.equals("")) {
                log.error("活动ID为空，无法进行支付！");
                throw new APIException("订单编号为空，无法进行支付！");
            }

            String urlPay = tActOrderService.wxPay(orderId,actId);
            log.info(urlPay);
            response.sendRedirect(urlPay);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new APIException("支付失败！");
    }


    /**
     * 接收通知的方法
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @PostMapping("/notifyUrl.do")
    public void notifyHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, String> params = UnionPayUtil.getRequestParams(request);
        System.out.println("params："+params);
        // 验签
        boolean checkRet = UnionPayUtil.checkSign(unionPay.getMd5Key(), params);
        if (checkRet) {
            //更新你们的订单
            tActOrderService.orderPaySucceed(params);//params.get("merOrderId")
        }
        // 收到通知后记得返回SUCCESS
        PrintWriter writer = response.getWriter();
        writer.print("SUCCESS");
        writer.flush();
    }

}
